<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0,shrink-to-fit=no, viewport-fit=cover">
    <meta name="keywords" content="蓝桥到家">
    <meta name="description" itemprop="description" content="生鲜副食、饮品乳品、鲜花蛋糕">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>新建收货地址</title>
    <link rel="stylesheet" type="text/css" href="../styles/reset.css"/>
    <link rel="stylesheet" type="text/css" href="../styles/iconfont/iconfont.css"/>
    <link rel="stylesheet" type="text/css" href="../styles/adderss.css"/>
    <link rel="stylesheet" type="text/css" href="../styles/common.css"/>
    <script type="text/javascript" src="../js/common.js"></script>
    <!-- 引入Vue -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        .error {
            color: #ff4d4f;
            font-size: 0.1rem;
            margin-top: 0.1rem;
            display: block;
        }
        .required {
            color: #ff4d4f;
            margin-right: 4px;
        }
    </style>
</head>

<body>
<div class="wrap" id="app">

    <!-- 头部 start -->
    <header class="header_bar">
        <a href="address.html">
            <div class="header_bar_back"></div>
        </a>
        <div class="header_bar_title">新建收货地址</div>
    </header>
    <!-- 头部 end -->
    <div class="container">
        <div class="form">
            <div class="form_item">
                <p><span class="required">*</span>所在省份:</p>
                <input v-model="addAddress.city"
                       type="text"
                       @blur="validateField('city')"
                       placeholder="请输入省份"/>
                <span class="error" v-if="errors.city">{{errors.city}}</span>
            </div>
            <div class="form_item">
                <p><span class="required">*</span>具体地址:</p>
                <input v-model="addAddress.address"
                       type="text"
                       @blur="validateField('address')"
                       placeholder="请输入具体地址"/>
                <span class="error" v-if="errors.address">{{errors.address}}</span>
            </div>
            <div class="form_item">
                <p><span class="required">*</span>联系姓名:</p>
                <input v-model="addAddress.name"
                       type="text"
                       @blur="validateField('name')"
                       placeholder="请输入联系人姓名"/>
                <span class="error" v-if="errors.name">{{errors.name}}</span>
            </div>
            <div class="form_item">
                <p><span class="required">*</span>联系电话:</p>
                <input v-model="addAddress.phone"
                       type="text"
                       @blur="validateField('phone')"
                       placeholder="请输入联系人电话"/>
                <span class="error" v-if="errors.phone">{{errors.phone}}</span>
            </div>
        </div>
    </div>
    <div class="">
        <button class="account" @click="add_address">保存收货地址</button>
    </div>
</div>
<script>
    const {createApp, ref} = Vue
    createApp({
        setup() {
            // 初始化地址数据 - ref对象会包装一个响应式对象
            const addAddress = ref({
                city: '',
                address: '',
                name: '',
                phone: ''
            })

            const errors = ref({
                city: '',
                address: '',
                name: '',
                phone: ''
            })

            const isLoading = ref(false)

            // 删除错误的重复初始化代码！
            // 原代码中这部分会把addAddress的值设置为undefined，因为错误地使用了addAddress.city而非addAddress.value.city

            const validateField = (field) => {
                errors.value[field] = '';
                // 访问ref对象的属性必须通过.value
                switch (field) {
                    case 'city':
                        if (!addAddress.value.city.trim()) {
                            errors.value.city = '请输入省份';
                        }
                        break;
                    case 'address':
                        if (!addAddress.value.address.trim()) {
                            errors.value.address = '请输入具体地址';
                        }
                        break;
                    case 'name':
                        if (!addAddress.value.name.trim()) {
                            errors.value.name = '请输入联系人姓名';
                        }
                        break;
                    case 'phone':
                        const phoneReg = /^1[3-9]\d{9}$/;
                        if (!addAddress.value.phone.trim()) {
                            errors.value.phone = '请输入手机号码';
                        } else if (!phoneReg.test(addAddress.value.phone.trim())) {
                            errors.value.phone = '请输入有效的手机号码';
                        }
                        break;
                }
            }

            const validateForm = () => {
                let isValid = true;

                ['city', 'address', 'name', 'phone'].forEach(field => {
                    validateField(field);
                    if (errors.value[field]) {
                        isValid = false;
                    }
                });

                return isValid;
            }

            const add_address = async () => {
                try {
                    if (!validateForm()) {
                        alert('请填写正确的信息');
                        return;
                    }

                    isLoading.value = true;

                    const addAddressResponse = await axios.post('http://localhost:3000/addAddress', {
                        city: addAddress.value.city.trim(),
                        address: addAddress.value.address.trim(),
                        name: addAddress.value.name.trim(),
                        phone: addAddress.value.phone.trim(),
                        createdAt: new Date().toISOString()
                    });

                    if ([200, 201].includes(addAddressResponse.status)) {
                        alert('添加成功');
                        window.location.href = 'address.html';
                    } else {
                        alert('添加失败，请稍后重试');
                    }

                } catch (error) {
                    console.error('添加地址出错:', error);
                    alert('网络错误，请检查连接后重试');
                } finally {
                    isLoading.value = false;
                }
            }

            return {
                addAddress,
                errors,
                isLoading,
                add_address,
                validateField,
                validateForm
            }
        }
    }).mount("#app")
</script>

</body>

</html>